<template>
    <a-form-model ref="form" :model="form" layout="vertical" class="rx-a-form-vertical">
        <a-form-model-item   :label="i18n('form.dataSource','数据源')" >
            <rx-input-button ref="dsName" v-model="form.dsName" @click="openDataSource" ></rx-input-button>
        </a-form-model-item>

        <a-form-model-item   :label="i18n('form.selectionTable','选择表')" >
            <rx-input-button ref="tableName" v-model="form.tableName" @click="onTableMap"></rx-input-button>
        </a-form-model-item>

        <a-form-model-item  :label="i18n('form.searchParams','搜索条件')">
            <div class="table-operator">
                <a-button @click="addConf">{{$ti18('rxList.add', '新增')}}</a-button>
                <a-button @click="removeConf">{{$ti18('rxList.delBtn','删除')}}</a-button>
            </div>
            <rx-grid
                ref="tableConf"
                :columns="columnsConf"
                :dataSource="form.whereFields"
                :allowRowSelect="true"
                :multiSelect="true"
                :showPage="false"
                :bordered="true"
                style="height:180px;"
            >
                <span slot="field" slot-scope="{text,record,index}">
                  <a-select v-model="record.field" :options="matchCol" @change="handWhereField($event, record)"
                            allowClear
                            :dropdown-menu-style="{width:'200px'}"
                            :dropdownMatchSelectWidth="false"
                  >
                  </a-select>
                </span>
                <span slot="valueSource" slot-scope="{text, record, index}">
                    <a-select :defaultValue="text" v-model="record.valueSource" style="width: 100%">
                      <a-select-option value="fields" :key="index">{{i18n('form.listFields','列表字段')}}</a-select-option>
                      <a-select-option value="fixedVar" :key="index">{{i18n('form.fixValue','固定值')}}</a-select-option>
                      <a-select-option value="script" :key="index">{{i18n('form.script','脚本')}}</a-select-option>
                      <a-select-option value="constantVar" :key="index">{{i18n('form.constVar','常量')}}</a-select-option>
                    </a-select>
               </span>
                <span slot="valueDef" slot-scope="{text, record, index}">
                    <a-input v-if="record.valueSource=='fixedVar'" :defaultValue="text" v-model="record.valueDef"/>
                    <a-input-group v-if="record.valueSource=='script'" compact>
                      <a-button @click="openScriptQuery(record)">...</a-button>
                    </a-input-group>
                    <a-select v-if="record.valueSource=='constantVar'" :defaultValue="text" :options="constantField"
                              v-model="record.valueDef" style="width: 100%"></a-select>
                    <a-select v-if="record.valueSource=='fields'" :defaultValue="text" :options="listFields"
                              v-model="record.bindField" style="width: 100%"></a-select>
               </span>

            </rx-grid>

        </a-form-model-item>
        <a-form-model-item  :label="i18n('list.conConfig','计算结果')">
                <a-button @click="openShowConf()">{{i18n('list.returnScript','配置')}}</a-button>
                <span v-if="form.template" class="is-seted">
                    <i class="iconfont iconsuccess_fill is-seted"></i>{{i18n('list.configured','已配')}}
                </span>
                <a-icon v-if="form.template" type="delete" style="margin-left: 10px;" @click="clearShowConf()"/>
        </a-form-model-item>


    </a-form-model>
</template>

<script>
import FormDbApi from "@/api/form/bo/formDb"
import { Dialog,  Util, App,JsConstant} from "@lowcode/jpaas-common-lib"
import showConfDialog from "@/views/modules/form/core/dialog/ShowConfDialog.vue";
import FormCustomQueryApi from '@/api/form/core/formCustomQuery'
import AppName from "@/assets/js/AppName.js";


export default {
    name: "renderConfig_relQuery",
    props: ["layerid", "destroy","curFields"],
    mixins:[App,AppName],
    computed: {
        table() {
            return this.$refs.table;
        },
        tableConf() {
            return this.$refs.tableConf;
        },
    },
    created() {

        //常量
        this.loadConstants();
    },
    data() {
        return {
            matchCol: [],

            form: {
               //数据源{text:"",value:""}
                dsName: "",
                //表 {text:"",value:""}
                tableName: "",
                //[{"idx_":"ovolpnq398637","conf":"TREE_ID_","valueSource":"fixedVar","valueDef":"1555397422375129089",dataType:""}]"
                whereFields: [],
                //模板
                template: "",
            },
            columnsConf: [
                {
                    title: this.$comi18('listDef.field', '字段'),
                    dataIndex: 'field',
                    allowCellEdit: false,
                    width: 100,
                    scopedSlots: {customRender: 'field'}
                },
                {
                    title: this.$comi18('formDef.valueSource', '值来源'),
                    dataIndex: 'valueSource',
                    allowCellEdit: false,
                    width: 100,
                    scopedSlots: {customRender: 'valueSource'}
                },
                {
                    title: this.i18n('form.defValue','默认值'),
                    dataIndex: 'valueDef',
                    allowCellEdit: false,
                    width: 100,
                    scopedSlots: {customRender: 'valueDef'}
                }
            ],
            constantField: [{label: this.i18n('form.validConst','可用常量'), value: ''}],
            listFields:this.curFields
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formCellRender",key);
        },
        validate(callback) {
            var self = this;
            callback();
        },
        openDataSource(vm) {
            Dialog.openDataSourceDialog({
                curVm: this, widthHeight: ['1200px', '600px'],
                data: {appName: this.serviceName}
            }, function (self, data) {
                vm.setVal(data.alias, data.name)
            })
        },
        onTableMap(vm) {
            var datasource;
            if (this.form.dsName != undefined && this.form.dsName.indexOf("{")>-1) {
                datasource = JSON.parse(this.form.dsName).value;
            } else {
                datasource = this.form.dsName;
            }
            Dialog.openTableQueryDialog({
                curVm: this, widthHeight: ['1200px', '600px'], data: {ds: datasource}
            }, function (self, data) {
                vm.setVal(data.tableName, data.tableName);
                self.loadColumn(data.tableName);
            })
        },
        loadColumn(tableName) {
            var self_ = this;
            var datasource = "";
            if(this.form.dsName) {
                datasource = JSON.parse(this.form.dsName).value;
            }
            FormDbApi.getByName("dsName=" + datasource + "&tbName=" + tableName).then(data => {
                var column = [];
                for (var i = 0; i < data.columnList.length; i++) {
                    let col = data.columnList[i];
                    column.push({label: col.comment, value: col.fieldName, dataType: col.columnType});
                }
                self_.matchCol = column;
            })
        },
        getField(field) {
            let fields = this.matchCol.filter(item => {
                return item.value == field;
            });
            if (fields && fields.length > 0) {
                return fields[0]
            }
            return null;
        },
        setData(data, fields) {
            Object.assign(this.form,data)
            //this.form = data
            if (data.tableName) {
                let tableObj = JSON.parse(data.tableName);
                let table = tableObj.value;
                this.loadColumn(table);
            }
        },
        addConf() {
            let _idx = Util.randomId();
            let obj = {idx_: _idx, field: "", valueSource: "", valueDef: "", dataType: ""};
            this.form.whereFields.push(obj);
        },
        removeConf() {
            this.tableConf.removeRows();
            let rows = this.tableConf.getData();
            this.form.whereFields = rows;

        },
        handWhereField(val, record) {
            let field = this.getField(val);
            record.dataType = field.dataType;
        },
        openScriptQuery(record) {
            let script = record.valueDef;
            Dialog.openScripttextDialog({
                curVm: this, widthHeight: ['800px', '600px'], data: {script: script}
            }, function (self, data) {
                record.valueDef = data;
            })
        },
        openShowConf() {
            var self=this;
            let obj={
                curVm: this,
                widthHeight: ['800px', '600px'],
                data: {
                    script:this.form.template,
                    mainField:this.curFields,
                    relField:this.matchCol,
                },
                component:showConfDialog,
                title:this.$ti18('rxForm.scriptContent','脚本内容')
            }
            Util.open(obj,function(action){
                if(action!='ok')return;
                const scripts=this.getScripts();
                self.form.template=scripts
            });

        },
        clearShowConf(){
            this.form.template=""
        },
        loadConstants() {
            FormCustomQueryApi.getConstants().then(data => {
                this.constantField = this.constantField.concat(data.map(item => {
                    return {label: item.val, value: item.key}
                }));
            })
        },
        getData() {
            return this.form;
        },

    }
}
</script>

<style scoped>
.is-seted {
    color: #70b90b;
    margin-left: 5px;
}
.ant-form-item{
    margin-bottom: 2px !important;
}
</style>